import axios from "axios";
import { ElMessageBox } from "element-plus";
import NProgress from "nprogress";
//配置axios
let http = axios.create({
  baseURL: "/api",
  timeout: 1000 * 10,
  withCredentials: true,
});

//配置拦截器

//请求拦截器
http.interceptors.request.use((config) => {
  //先获取token
  NProgress.start();
  let token = sessionStorage.getItem("myx-token");
  config.headers.authorization = token;
  // console.log(config);
  return config;
});
//响应拦截器
http.interceptors.response.use((config) => {
  NProgress.done();
  if (config.data.state) {
    //响应正常
    return config;
  } else {
    //不需要弹框提示的路径
    let excludePaths = ["/sms/send", "/order/query_order_status"];

    if (!excludePaths.includes(config.config.url)) {
      //响应了错误
      ElMessageBox.alert(config.data.msg, "错误提示", { type: "error" });
    }
    //判断登入失效的情况 10022(登入状态过期) 1004(token失效了)前后端通俗约定状态码 并不是http状态码

    if (config.data.code == "10022" || config.data.code == "1004") {
      //退到登入页,然后清掉token
      sessionStorage.removeItem("myx-token");
      router.push("/login");
      //刷新页面,清掉缓存
      location.reload();
    }
    return Promise.reject(config.data.msg);
  }
});

export default http;
